# -*- coding: utf-8 -*-
__author__ = 'Paul'
import random
from zope import schema
from zope.formlib import form
from zope.interface import implements
from zope.component import getMultiAdapter
from plone.app.portlets.portlets import base
from plone.memoize.instance import memoize
from plone.portlets.interfaces import IPortletDataProvider
from DateTime import DateTime
from Products.Five.browser.pagetemplatefile import\
    ViewPageTemplateFile
from Products.CMFCore.utils import getToolByName
from Products.bpContents import _
from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
from Acquisition import aq_inner
from plone.memoize.compress import xhtml_compress
from Products.bpContents.aviso import IAviso
from Products.ATContentTypes.interfaces import IATDocument
from zope.site.hooks import getSite
from OFS.interfaces import IOrderedContainer
import unicodedata


class IAvisosPortlet(IPortletDataProvider):
    count = schema.Int(title=_(u'Number of items to display'),
        description=_(u'How many items to list.'),
        required=True,
        default=3)



class Assignment(base.Assignment):
    implements(IAvisosPortlet)

    def __init__(self, count=5,canal=[], categoria=[]):
        self.count = count

    @property
    def title(self):
        return _(u"Noticias por prioridad")

class Renderer(base.Renderer):
    render = ViewPageTemplateFile('aviso_portlet.pt')

    def __init__(self, *args):
        base.Renderer.__init__(self, *args)
        context = aq_inner(self.context)
        portal_state = getMultiAdapter((context, self.request), name=u'plone_portal_state')
        plone_tools = getMultiAdapter((context, self.request), name=u'plone_tools')
        self.catalog = plone_tools.catalog()
        self.anonymous = portal_state.anonymous()
        self.portal_url = portal_state.portal_url()

    @property
    def available(self):
        return True

    def recent_items(self):
        return self._data()

    def recently_modified_link(self):
        return '%s/recently_modified' % self.portal_url

    def getAvisos(self):
        listMeses=["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Setiembre","Octubre","Noviembre","Diciembre"]
        rex=[]
        for avi in self._data():
            imgObj=self.context.unrestrictedTraverse(avi.getPath())
            resunen=avi.Description


            fchArr=avi.Date.split("-")
            diaA=fchArr[2][:fchArr[2].find("T")]
            mesA=listMeses[int(fchArr[1])-1]
            prtF="%s de %s, %s" %(diaA,mesA,fchArr[0])
            listIMG=self.parseForIMG(imgObj)
            if len(listIMG)>0:
                imgF=listIMG[0]
            else:
                imgF=""

            rex.append({
                "fecha":prtF,
                "titulo":avi.Title,
                "url":avi.getPath(),
                "descri":resunen,
                "position":self.get_position_in_parent(imgObj),
                "img":imgF
            })

        return rex

    def getNoticiaURL(self):
        ###devulve la dirección de la carpeta Noticias
        s=self.catalog(id="noticias", portal_type="Folder")
        if len(s)>0:
            return s[0].getPath()
        else:
            return None

    @memoize
    def _data(self):
        limit = self.data.count
        home=getSite()
        try:
            homeFolder=home["home"]["conocenos"]
        except :
            return []

        if homeFolder.has_key("noticias"):
            folderAvisos=["noticias"]
        else:
            homeFolder.invokeFactory(id="noticias",
                type_name="Folder",
                title="Noticias",
                description=u"Información util para a los usuarios")

            from Products.ATContentTypes.lib import constraintypes
            try:
                homeFolder["avisos"].setConstrainTypesMode(constraintypes.ENABLED)
                homeFolder["avisos"].setLocallyAllowedTypes(["Products.bpContents.aviso","Document"])
                homeFolder["avisos"].setImmediatelyAddableTypes(["Products.bpContents.aviso","Document"])
                homeFolder["avisos"].reindexObject()
            except :
                print "no pudo crearse la carpeta AVISOS"
                return []


        query = dict(object_provides=(IAviso.__identifier__,IATDocument.__identifier__))
        query['sort_on'] = 'Date'
        query['sort_limit'] = limit
        query['sort_order'] = 'reverse'
        query['path']='/'.join(homeFolder["noticias"].getPhysicalPath())


        result=self.catalog(query)
        tmpB=[]
        tmpM=[]
        tmpA=[]

        for avO in result:
            try:
                if avO.getObject().prioridad=="Alta":
                    tmpA.append(avO)
                elif avO.getObject().prioridad=="Media":
                    tmpM.append(avO)
                else:
                    tmpB.append(avO)
            except:
                tmpM.append(avO)

        final=tmpA+tmpM+tmpB

        return final



    def get_position_in_parent(self,obj):
        """ Use IOrderedContainer interface to extract the object's manual ordering position
        """
        parent = obj.aq_inner.aq_parent
        ordered = IOrderedContainer(parent, None)
        if ordered is not None:
            return ordered.getObjectPosition(obj.getId())
        return 0


    def parseForIMG(self,docu):
        from lxml import etree
        from lxml.html import fromstring, tostring
        portal_transforms=getToolByName(self.context, 'portal_transforms')
        if docu.portal_type=="Document":
            text = docu.getText()
        else:
            text = docu.cuerpo.raw
        data = portal_transforms.convertTo('text/html', text, mimetype='text/-x-web-intelligent')
        html = data.getData()
        parseado=etree.HTML(html)

        imgs=[]

        for element in parseado.iter("*"):
            if element.tag=="img":
                titulo=""
                if "title" in element.keys():
                    titulo=element.attrib["title"]

                imgs.append({"src":element.attrib["src"],"titulo":titulo})

        return imgs

class AddForm(base.AddForm):
    form_fields = form.Fields(IAvisosPortlet)
    label = _(u"Add Recent Portlet")
    description = _(u"This portlet displays recently modified content.")

    def create(self, data):
        return Assignment(count=data.get('count', 3))

class EditForm(base.EditForm):
    form_fields = form.Fields(IAvisosPortlet)
    label = _(u"Edit Recent Portlet")
    description = _(u"This portlet displays recently modified content.")